# -*- coding: UTF-8 -*-
# Author: Damon(wuud1)
# CreateDate: 
# Message:
import json
from pprint import pprint
from base_class import BaseClass

class GetVindataExtraInfo(BaseClass):

    def __init__(self, **kwargs):
        self.db_config = kwargs.get("db_config")
        self.conn, self.curs = self.get_conn_curs(db_config=self.db_config, type='dict')
        self.num = 0
        self.name_dict = {}

    def get_name_dict(self):
        sql = '''select `name`,`condition`,`code`,`brandCode` from `cars_info_collection`'''
        self.curs.execute(sql)
        data = self.curs.fetchall()
        self.name_dict = {i.get("code"):{"name":i.get("name")+"$$"+i.get("condition"), "brandCode":i.get("brandCode")} for i in data}

    def get_vin_data_list(self):
        sql = '''select * from `vindat`;'''
        self.curs.execute(sql)
        data = self.curs.fetchall()
        return data

    def get_posname_dict(self):
        sql = '''select * from `posname`;'''
        self.curs.execute(sql)
        data = self.curs.fetchall()
        # _dict = {i.get("F2").strip() if i.get("F2") else "" + i.get("F3").strip() if i.get("F3") else "" :{"F11":i.get("F11").strip() if i.get("F11") else "" , "F4":i.get("F4").strip() if i.get("F4") else "" , "engine":i.get("F5").strip() if i.get("F5") else "" , "trans":i.get("F7").strip() if i.get("F7") else "" , "driver":i.get("F9") if i.get("F9") else "" , "grade":i.get("F10").strip() if i.get("F10") else "" , "area":i.get("F12").strip() if i.get("F12") else "" } for i in data}
        # _dict = {i.get("trim(F2)") + i.get("trim(F3)") if i.get("trim(F3)") else "" :{"F11":i.get("trim(F11)") if i.get("trim(F11)") else "" , "F4":i.get("trim(F4)") if i.get("trim(F4)") else "" , "engine":i.get("trim(F5)") if i.get("trim(F5)") else "" , "trans":i.get("trim(F7)") if i.get("trim(F7)") else "" , "driver":i.get("trim(F9)") if i.get("trim(F9)") else "" , "grade":i.get("trim(F10)") if i.get("trim(F10)") else "" , "area":i.get("trim(F12)") if i.get("trim(F12)") else "" } for i in data}
        _dict = {i.get("f2").strip() + i.get("f3").strip() :[] for i in data}
        for i in data:
            _key = i.get("f2").strip() + i.get("f3").strip()
            #_dict[_key].append({"F11":i.get("trim(F11)") if i.get("trim(F11)") else "" , "body":i.get("trim(F4)") if i.get("trim(F4)") else "" , "engine":i.get("trim(F5)") if i.get("trim(F5)") else "" , "trans":i.get("trim(F7)") if i.get("trim(F7)") else "" , "driver":i.get("trim(F9)") if i.get("trim(F9)") else "" , "grade":i.get("trim(F10)") if i.get("trim(F10)") else "" , "area":i.get("trim(F12)") if i.get("trim(F12)") else "" })
            data_dict = dict(
                body=i.get("f4").strip(),
                engine=i.get("f5").strip(),
                trans=i.get("f7").strip(),
                driver=i.get("f9").strip(),
                grade=i.get("f10").strip(),
                area=i.get("f12").strip(),
            )
            sa_list = []
            i.pop("f1")
            i.pop("f2")
            for j in i.values():
                if j.strip() == '':
                    continue
                sa_list.append(j.strip())

            sa = '.'.join(set(sa_list))
            data_dict['filter_code'] = sa
            _dict[_key].append(data_dict)
        return _dict

    def run(self):
        print("程序启动...")
        posname_dict = self.get_posname_dict()
        # pprint(posname_dict)
        self.get_name_dict()
        vin_data_list = self.get_vin_data_list()
        print("开始循环...")
        for vin_data in vin_data_list:
            cid = vin_data.get("f4").strip()
            kid_car = vin_data.get("f8").strip()
            years = vin_data.get("f7").strip()
            color_code = vin_data.get("f6").strip()
            _key = cid+kid_car
            # print(_key)
            extra_info = posname_dict.get(_key, [])
            extra_info_new = []
            for i in extra_info:
                i['years'] = years
                extra_info_new.append(i)

            ######
            body = extra_info[0].get("body") if len(extra_info) > 0 else ""
            engine = extra_info[0].get("engine") if len(extra_info) > 0 else ""
            trans = extra_info[0].get("trans") if len(extra_info) > 0 else ""
            driver = extra_info[0].get("driver") if len(extra_info) > 0 else ""
            area = extra_info[0].get("area") if len(extra_info) > 0 else ""

            vin = vin_data.get("f2").strip()
            shortvin = vin[-7:]
            name = self.name_dict[cid]["name"].replace("$$","")
            name1 = self.name_dict[cid]["name"].split("$$")[0]

            brandCode = self.name_dict[cid]["brandCode"]
            year = years
            # maindata = '{"车型版本":'+"%s"%name+', "年份":'+"%s"%years+',"车身":'+"%s"%body+' ,"发动机":'+"%s"%engine+',"变速箱":'+"%s"%trans+',"驱动":'+"%s"%driver+',"地区":'+"%s"%area+'}'
            maindata = '{"车型版本":'+'"{}"'.format(name1)+', "年份":'+'"{}"'.format(years)+',"车身":'+'"{}"'.format(body)+',"颜色代号":'+'"{}"'.format(color_code)+' ,"发动机":'+'"{}"'.format(engine)+',"变速箱":'+'"{}"'.format(trans)+',"驱动":'+'"{}"'.format(driver)+',"地区":'+'"{}"'.format(area)+'}'
            subdata = json.dumps({})
            code = cid
            # vin = vin_data.get(""),
            # vin = vin_data.get(""),
            # vin = vin_data.get(""),
            _dict = dict(
                vin=vin,
                shortvin=shortvin,
                name=name,
                brandCode=brandCode,
                year=year,
                maindata=maindata,
                subdata=subdata,
                formatdata=json.dumps({}),
                imgname='',
                code=code,
                extra_info=json.dumps(extra_info_new),
                updatetime="now()",
                createtime="now()",
            )

            ######


            insert_sql = self.construct_insert_sql("cars_vin_info", _dict)

            try:
                self.curs.execute(insert_sql)
                self.num += 1
            except Exception as e:
                print(insert_sql)
                raise e

            if self.num % 10000 == 0:
                self.conn.commit()
                print("提交insert缓存, 当前数量: {}".format(self.num))
        self.conn.commit()
        print("最终提交, 总数据量: {}".format(self.num))


if __name__ == '__main__':
    db_config = dict(
        host="127.0.0.1",
        port=3306,
        user="root",
        passwd="123456",
        db="nissan_new",
        charset="utf8",
    )
    tools = GetVindataExtraInfo(db_config=db_config)
    tools.run()


